// GameManager.ts
import { _decorator, Component, Node, Prefab, instantiate, math } from 'cc';
import { Player } from './Player';
import { UIManager } from './UIManager';
import { GameEvent } from './EventType';
import { ScoreManager } from './ScoreManager';
import { ObstacleData } from './ObstacleData';

const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {
    @property({ type: Player, tooltip: "玩家角色组件" })
    player: Player = null!;

    @property({ type: Prefab, tooltip: "障碍物预制体" })
    obstaclePrefab: Prefab = null!;

    @property({ type: Node, tooltip: "障碍物父节点" })
    obstaclesParent: Node = null!;

    @property({ type: ScoreManager })
    scoreManager: ScoreManager = null!;

    @property({ tooltip: "障碍物生成间隔（秒）" })
    spawnInterval: number = 1.5;

    // 初始障碍物配置
    @property({ tooltip: "初始障碍物数量" })
    initialObstacleCount: number = 8;

    @property({ tooltip: "初始障碍物距离中心的比例（相对于玩家初始半径）" })
    initialObstacleRadiusRatio: number = 0.3; // 更靠近中心

    // 移动障碍物配置
    @property({ tooltip: "障碍物最小移动速度" })
    minObstacleSpeed: number = 30;

    @property({ tooltip: "障碍物最大移动速度" })
    maxObstacleSpeed: number = 80;

    private spawnTimer: number = 0;
    private isGameRunning: boolean = false;

    start() {
        // 监听UI事件
        if (UIManager.instance) {
            const uiEventTarget = UIManager.instance.getEventTarget();
            uiEventTarget.on(GameEvent.GAME_START, this.onGameStart, this);
            uiEventTarget.on(GameEvent.GAME_RESTART, this.onGameRestart, this);
        }

        this.initGame();
    }

    update(deltaTime: number) {
        if (!this.isGameRunning) return;

        this.spawnTimer += deltaTime;

        // 生成新的移动障碍物
        if (this.spawnTimer >= this.spawnInterval) {
            this.spawnTimer = 0;
            this.spawnMovingObstacle();
        }

        // 每秒增加分数
        if (Math.floor(this.spawnTimer) === 1) {
            this.scoreManager.addScore(1);
        }

        // 更新所有移动障碍物的位置
        this.updateMovingObstacles(deltaTime);
    }

    // 初始化游戏
    public initGame() {
        this.scoreManager.resetScore();
        this.isGameRunning = false;
        this.spawnTimer = 0;
        this.obstaclesParent.destroyAllChildren();
        this.player.obstacles = [];
        this.player.resetPlayerState();
        
        // 生成初始8个固定障碍物
        this.spawnInitialObstacles();
    }

    // 生成初始固定障碍物（不移动）
    private spawnInitialObstacles() {
        if (!this.obstaclePrefab || !this.player) return;

        const angleStep = 360 / this.initialObstacleCount; // 45度间隔

        for (let i = 0; i < this.initialObstacleCount; i++) {
            const angle = i * angleStep;
            const rad = angle * (Math.PI / 180);
            const radius = this.player.radius * this.initialObstacleRadiusRatio;

            // 计算位置
            const x = Math.sin(rad) * radius;
            const y = Math.cos(rad) * radius;

            // 实例化障碍物
            const obstacle = instantiate(this.obstaclePrefab);
            obstacle.parent = this.obstaclesParent;
            obstacle.position = new math.Vec3(x, y, 0);

            // 添加数据组件，标记为固定障碍物
            const obstacleData = obstacle.addComponent(ObstacleData);
            obstacleData.isFixed = true;

            this.player.addObstacle(obstacle);
        }
    }

    // 生成移动的障碍物
    private spawnMovingObstacle() {
        if (!this.obstaclePrefab || !this.player) return;

        const obstacle = instantiate(this.obstaclePrefab);
        obstacle.parent = this.obstaclesParent;

        // 随机初始位置（玩家初始半径处）
        const randomAngle = math.randomRange(0, 360);
        const rad = randomAngle * (Math.PI / 180);
        const x = Math.sin(rad) * this.player.radius;
        const y = Math.cos(rad) * this.player.radius;
        obstacle.position = new math.Vec3(x, y, 0);

        // 添加数据组件，标记为移动障碍物并设置随机速度
        const obstacleData = obstacle.addComponent(ObstacleData);
        obstacleData.isFixed = false;
        obstacleData.moveSpeed = math.randomRange(this.minObstacleSpeed, this.maxObstacleSpeed);

        this.player.addObstacle(obstacle);
    }

    // 更新所有移动障碍物的位置（向中心移动）
    private updateMovingObstacles(deltaTime: number) {
        // 遍历所有障碍物
        for (let i = this.obstaclesParent.children.length - 1; i >= 0; i--) {
            const obstacle = this.obstaclesParent.children[i];
            if (!obstacle.isValid) continue;

            // 获取障碍物数据组件
            const obstacleData = obstacle.getComponent(ObstacleData);
            if (!obstacleData) continue;

            // 只处理非固定障碍物
            if (!obstacleData.isFixed) {
                // 计算向中心的方向向量（归一化）
                const centerDir = new math.Vec3(
                    -obstacle.position.x,
                    -obstacle.position.y,
                    0
                ).normalize();

                // 计算移动步长并更新位置
                const moveStep = centerDir.multiplyScalar(obstacleData.moveSpeed * deltaTime);
                obstacle.position = obstacle.position.add(moveStep);

                // 到达中心附近（距离 < 10）时销毁
                if (obstacle.position.length() < 10) {
                    this.player.removeObstacle(obstacle);
                    obstacle.destroy();
                }
            }
        }
    }

    // 游戏开始
    private onGameStart() {
        this.isGameRunning = true;
        this.player.startMovingToCenter();
    }

    // 游戏重启
    private onGameRestart() {
        this.initGame();
        this.isGameRunning = true;
        this.player.startMovingToCenter();
    }

    // 游戏结束
    gameOver() {
        this.isGameRunning = false;
        UIManager.instance?.showGameOver(this.scoreManager.getScore());
    }

    onDestroy() {
        if (UIManager.instance) {
            const uiEventTarget = UIManager.instance.getEventTarget();
            uiEventTarget.off(GameEvent.GAME_START, this.onGameStart, this);
            uiEventTarget.off(GameEvent.GAME_RESTART, this.onGameRestart, this);
        }
    }
}
